/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.cbm.smsbroadcast;

import com.elcom.emocbc.util.ConfigurationManager;
import com.elcom.smpp.pdu.AlertNotification;
import com.elcom.smpp.pdu.CancelSMResp;
import com.elcom.smpp.pdu.DataSM;
import com.elcom.smpp.pdu.DataSMResp;
import com.elcom.smpp.pdu.DeliverSM;
import com.elcom.smpp.pdu.QuerySMResp;
import com.elcom.smpp.pdu.ReplaceSMResp;
import com.elcom.smpp.pdu.SubmitMultiSMResp;
import com.elcom.smpp.pdu.SubmitSM;
import com.elcom.smpp.pdu.SubmitSMResp;
import com.elcom.smpp.smppclient.SmppClientMain;
import com.elcom.smpp.smppclient.data.SessionCfg;
import com.elcom.smpp.smppclient.data.SmscCfg;
import com.elcom.smpp.smppclient.level1.MessageListener;
import com.elcom.smpp.smppclient.level3.SDManager;
import java.util.concurrent.atomic.AtomicInteger;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class SmppClient implements MessageListener {

    private SmppClientMain smppclient;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static SmppClient instance;
    private AtomicInteger sequence;

    public static synchronized SmppClient getInstance() {
        if (instance == null) {
            instance = new SmppClient();
        }
        return instance;
    }

    private SmppClient() {
        try {
            ConfigurationManager.reloadConfiguration();
            String smppConfigPath = ConfigurationManager.getStrProp("cell_broadcast", "smppConfigPath", "/home/liveinfo/config/cellbroadcast/smppclient.cfg");
//            String smppConfigPath = Constant.CONFIG_FOLDER + "smppclient.cfg";
//            String smppRuleName = ConfigurationManager.getStrProp("cell_broadcast", "smppRuleName", "/home/liveinfo/config/cellbroadcast/smppclient.cfg");
            smppclient = new SmppClientMain(logger, "SmsBroadcaster", smppConfigPath, this, null);
            smppclient.execute();

            sequence = new AtomicInteger(0x262f7e);
        } catch (Throwable ex) {
            logger.error("", ex);
        }
    }

    public void send(String shortcode, String msisdn, byte[] message) {
        SubmitSM submit = new SubmitSM();
        submit.setSequenceNumber(sequence.incrementAndGet());
        submit.setSourceAddr(shortcode);
        submit.setSourceAddrTon((byte) 0x01);
        submit.setSourceAddrNpi((byte) 0x01);
        submit.setDestAddr(msisdn);
        submit.setDestAddrTon((byte) 0x01);
        submit.setDestAddrNpi((byte) 0x01);
        submit.setDataCoding((byte) 0xf6);
        submit.setProtocolId((byte) 0x7f);
        submit.setRegisteredDelivery((byte) 0x02);
        submit.setValidityPeriod("000000000900000R");
        submit.setShortMessage(message);
        send(submit);
    }

    private void send(SubmitSM submit) {
        try {
            logger.info("Sending SMS {}", submit);
            int sentResult = smppclient.getSMSCManager().requestSm(submit);
            if (sentResult != 0) {
                String detail = SDManager.SENT.errorText(sentResult);
                logger.error((new StringBuilder("Failed to sent -- ")).append(submit).append(" (").append(detail).append(")").toString());
            } else {
                logger.info("Successfully send SMS to {}", submit.getDestAddr());
            }
        } catch (Throwable t) {
            logger.error((new StringBuilder("Send exception: ")).append(submit).toString(), t);
        }
    }

    @Override
    public void onDataSm(DataSM datasm, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onDeliverSm(DeliverSM dsm, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onAlertNotification(AlertNotification an, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onDataSmResp(DataSMResp dsmr, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onSubmitSmResp(SubmitSMResp ssmr, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onSubmitMultiSmResp(SubmitMultiSMResp smsmr, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onReplaceSmResp(ReplaceSMResp rsmr, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onCancelSmResp(CancelSMResp csmr, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }

    @Override
    public void onQuerySmResp(QuerySMResp qsmr, SmscCfg sc, SessionCfg sc1, ChannelHandlerContext chc, MessageEvent me) {
    }
}
